/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.taobao.batch.BuildFeedItemJob
   Module Description   :

   Date Created      : 2011/3/24
   Original Author   : jeffma
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.taobao.batch;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.thread.batch.AbstractRunJob;
import com.yaodian100.ec.taobao.service.TaobaoService;

/**
 * @author jeffma
 * 
 */
public class BuildFeedItemJob extends AbstractRunJob {

	private TaobaoService taobaoService;
	private String percentage;
	private int minSpecInv;
	private boolean full;

	/** default constructor */
	public BuildFeedItemJob(TaobaoService taobaoService, String percentage, int minSpecInv, boolean full) {
		super("BuildFeedItem");
		this.taobaoService = taobaoService;
		this.percentage = percentage;
		this.minSpecInv = minSpecInv;
		this.full = full;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.core.thread.batch.AbstractRunJob#execute()
	 */
	@Override
	public void execute() {
		String feedRootPath = ServerValue.getFrontApachePath() + "3party_ex" + File.separator + "taobao";
		String feedItemFolderPath = feedRootPath + File.separator + "item" + File.separator;

		// 更新所有 item file
		Map<String, String> operation = new HashMap();

		Map<String, Date> existProducts = new HashMap();
		Iterator<File> it = FileUtils.iterateFiles(new File(feedItemFolderPath), new String[] { "xml" }, false);
		while (it.hasNext()) {
			File f = it.next();
			String productId = StringUtils.split(f.getName(), ".")[0];
			existProducts.put(productId, new Date(f.lastModified()));
		}

		List<Map<String, Object>> publishProd = taobaoService.getPublishProduct(percentage, minSpecInv);
		logger.info("build product size:{}, exist feed size:{}", publishProd.size(), existProducts.size());
		for (Map<String, Object> pMap : publishProd) {
			String feedItemPath = feedItemFolderPath + pMap.get("PRODUCT_ID") + ".xml";
			File feedItemFile = new File(feedItemPath);

			Date feedModifyDate = existProducts.get(pMap.get("PRODUCT_ID"));
			Date shelfModify = (Date) pMap.get("SHELF_MODIFY");
			Date productModify = (Date) pMap.get("PRODUCT_MODIFY");
			if (feedModifyDate != null && shelfModify.before(feedModifyDate) && productModify.before(feedModifyDate)) {
				operation.put(pMap.get("PRODUCT_ID").toString(), "skip");
				existProducts.remove(pMap.get("PRODUCT_ID").toString());
				// 資料無更新, skip upload
				continue;
			} else if (feedModifyDate == null) {
				logger.info("build product new feed: product modify:{}, shelf modify:{}", new Object[] { productModify,
						shelfModify });
			} else {
				logger.info("update build product feed: product modify:{}, shelf modify:{}, feed modify:{}", new Object[] {
						productModify, shelfModify, feedModifyDate });
			}

			// old item, check modifyDate
			String feedItem = taobaoService.buildFeedItem(pMap, feedModifyDate);
			try {
				if (StringUtils.isNotBlank(feedItem)) {
					// 資料有更新, 刪除 feed item 重新建立
					if (feedItemFile.exists()) {
						FileUtils.forceDelete(feedItemFile);
					}
					FileUtils.writeStringToFile(feedItemFile, feedItem);
					operation.put(pMap.get("PRODUCT_ID").toString(), "update");
				} else {
					logger.error("build " + feedItemPath + " fail, not context");
				}
				existProducts.remove(pMap.get("PRODUCT_ID").toString());
			} catch (IOException e) {
				logger.error("build " + feedItemPath + " fail, exception:" + e.getMessage(), e);
			}
		}
		logger.info("delete feed size:{}", existProducts.size());
		for (String pid : existProducts.keySet()) {
			String feedItemPath = feedItemFolderPath + pid + ".xml";
			File feedItemFile = new File(feedItemPath);
			try {
				if (feedItemFile.exists()) {
					FileUtils.forceDelete(feedItemFile);
				}
			} catch (IOException e) {
				logger.error("build " + feedItemPath + " fail, exception:" + e.getMessage(), e);
			}
			operation.put(pid, "delete");
		}

		if (full) {
			// 更新 FullIndex.xml
			String feedFullPath = feedRootPath + File.separator + "FullIndex.xml";
			File feedFullFile = new File(feedFullPath);
			if (feedFullFile.exists()) {
				String tmpFile = feedRootPath + File.separator + "bak" + File.separator + "FullIndex.xml."
						+ DateUtil.convertDateToString("yyMMddHHmm", new Date());
				try {
					FileUtils.moveFile(feedFullFile, new File(tmpFile));
				} catch (IOException e) {
					logger.error("backup " + tmpFile + " fail, exception:" + e.getMessage(), e);
				}
			}
			String feedFull = taobaoService.buildFeedHead("taobao/feed_full", operation);
			try {
				FileUtils.writeStringToFile(feedFullFile, feedFull);
			} catch (IOException e) {
				logger.error("build " + feedFullPath + " fail, exception:" + e.getMessage(), e);
			}
			logger.info("build {}, operation size:{}", feedFullPath, operation.size());
		} else {
			// 更新 IncrementIndex.xml
			String feedIncrementPath = feedRootPath + File.separator + "IncrementIndex.xml";
			File feedIncrementFile = new File(feedIncrementPath);
			if (feedIncrementFile.exists()) {
				String tmpFile = feedRootPath + File.separator + "bak" + File.separator + "IncrementIndex.xml."
						+ DateUtil.convertDateToString("yyMMddHHmm", new Date());
				try {
					FileUtils.moveFile(feedIncrementFile, new File(tmpFile));
				} catch (IOException e) {
					logger.error("backup " + tmpFile + " fail, exception:" + e.getMessage(), e);
				}
			}
			String feedIncrement = taobaoService.buildFeedHead("taobao/feed_increment", operation);
			try {
				FileUtils.writeStringToFile(feedIncrementFile, feedIncrement);
			} catch (IOException e) {
				logger.error("build " + feedIncrementPath + " fail, exception:" + e.getMessage(), e);
			}
			logger.info("build {}, operation size:{}", feedIncrementPath, operation.size());
		}

	}
}
